// 使用 require 避免模块解析问题
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useAppStore = defineStore('app', () => {
  // 状态
  const loading = ref(false)
  const networkStatus = ref(true)
  const pageTitle = ref('')
  const systemInfo = ref({})
  const theme = ref('light')

  // 计算属性 (getters)
  const isDarkTheme = computed(() => {
    return theme.value === 'dark'
  })

  const platform = computed(() => {
    return systemInfo.value.platform || 'unknown'
  })

  const statusBarHeight = computed(() => {
    return systemInfo.value.statusBarHeight || 0
  })

  // 方法 (actions)
  const setLoading = (isLoading) => {
    loading.value = isLoading
  }

  const setNetworkStatus = (status) => {
    networkStatus.value = status
  }

  const setPageTitle = (title) => {
    pageTitle.value = title
    // 设置导航栏标题
    uni.setNavigationBarTitle({
      title: title
    })
  }

  const setSystemInfo = (info) => {
    systemInfo.value = info
  }

  const setTheme = (newTheme) => {
    theme.value = newTheme
    uni.setStorageSync('theme', newTheme)
  }

  const showLoading = (title = '加载中...') => {
    setLoading(true)
    uni.showLoading({
      title,
      mask: true
    })
  }

  const hideLoading = () => {
    setLoading(false)
    uni.hideLoading()
  }

  const showToast = ({ title, icon = 'none', duration = 2000 }) => {
    uni.showToast({
      title,
      icon,
      duration
    })
  }

  const showModal = ({ title = '提示', content, showCancel = true }) => {
    return new Promise((resolve) => {
      uni.showModal({
        title,
        content,
        showCancel,
        success: (res) => {
          resolve(res.confirm)
        }
      })
    })
  }

  const getSystemInfo = () => {
    uni.getSystemInfo({
      success: (res) => {
        setSystemInfo(res)
      }
    })
  }

  const checkNetworkStatus = () => {
    uni.getNetworkType({
      success: (res) => {
        setNetworkStatus(res.networkType !== 'none')
      }
    })
  }

  return {
    // 状态
    loading,
    networkStatus,
    pageTitle,
    systemInfo,
    theme,
    // 计算属性
    isDarkTheme,
    platform,
    statusBarHeight,
    // 方法
    setLoading,
    setNetworkStatus,
    setPageTitle,
    setSystemInfo,
    setTheme,
    showLoading,
    hideLoading,
    showToast,
    showModal,
    getSystemInfo,
    checkNetworkStatus
  }
})